package com.vonchenchen.simple_downloader.downloader;

import android.content.Context;
import android.util.Log;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;

/**
 * Created by lidechen on 9/15/16.
 */
public class FileUtils {

    private static Context mContext;

    public static void init(Context context){
        mContext = context;
    }

    /**
     * 将线程信息用json格式记录在特定文件中
     * @param threadInfo
     */
    public static void recordThreadInfo(ThreadInfo threadInfo){
        File targetFile = new File(DownLoadManager.PATH_DOWNLOAD_INFO+"ThreadInfo_"+threadInfo.threadId);
        if(targetFile.exists()){
            targetFile.delete();
            targetFile = new File(DownLoadManager.PATH_DOWNLOAD_INFO+"ThreadInfo_"+threadInfo.threadId);
        }
        writeStringToFile(threadInfo.toJsonString(), targetFile);
    }

    /**
     * 读取存储的线程信息
     * @param threadId
     * @return
     */
    public static ThreadInfo getThreadInfoByThreadId(int threadId){
        File targetFile = new File(DownLoadManager.PATH_DOWNLOAD_INFO+"ThreadInfo_"+threadId);
        if(targetFile.exists()){
            FileInputStream inputStream = null;
            try {
                inputStream = new FileInputStream(targetFile);
                byte[] b = new byte[inputStream.available()];
                String infoJson = new String(b);
                JSONObject jsonObject = new JSONObject(infoJson);

                ThreadInfo threadInfo = new ThreadInfo();
                threadInfo.startPos = jsonObject.getLong("startPos");
                threadInfo.currPos = jsonObject.getLong("currPos");
                threadInfo.endPos = jsonObject.getLong("endPos");
                threadInfo.url = new URL(jsonObject.getString("url"));
                threadInfo.threadId = jsonObject.getInt("threadId");
                threadInfo.targetFile = new File(jsonObject.getString("targetFile"));

                return threadInfo;
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    public static void writeStringToFile(String logContent, File targetFile){
        OutputStreamWriter osw;

        if (!targetFile.exists()) { //今天日志不存在
            try {
                StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
                StackTraceElement caller = stacks[4];

                targetFile.createNewFile();

                osw = new OutputStreamWriter(new FileOutputStream(targetFile), "utf-8");
                osw.write(logContent);
                osw.flush();
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {                    //今天日志存在
            try {
                osw = new OutputStreamWriter(new FileOutputStream(targetFile, true), "utf-8");
                osw.write(logContent);
                osw.flush();
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取文本文件
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String read(Context context, String fileName) {
        try {
            FileInputStream in = context.openFileInput(fileName);
            return readInStream(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String readInStream(FileInputStream inStream) {
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[512];
            int length = -1;
            while ((length = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, length);
            }

            outStream.close();
            inStream.close();
            return outStream.toString();
        } catch (IOException e) {
            Log.i("FileTest", e.getMessage());
        }
        return null;
    }

    public byte[] readFileData(String path) {
        try {
            File file = new File(path);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] b = new byte[inputStream.available()];
            return b;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
